<script setup>
import PageHeader from "./components/pageHeader.vue";
import PageContent from "./components/pageContent.vue";
import {validList, validSurvey} from "./utils/index.js";
import {ElMessageBox} from "element-plus";
import {saveSurveyIssueApi, updateSurveyApi} from "@/api/feedback/survey.js";
const {proxy}  = getCurrentInstance();
const pageContentRef = ref(null)
const route = useRoute();
const surId = computed(()=>route.query.surId)
const activeIndex = ref(0)

// 保存
const handlerSave =  async()=>{
  const data = formatData();
  // 保存题目数据
  await saveSurveyIssueApi({
    surId: +surId.value,
    data
  })
  // 保存问卷修改
  await updateSurveyApi(pageContentRef.value.surveyData)
  proxy.$modal.msgSuccess("保存成功")
  pageContentRef.value.initData();
}

// 校验处理
const validateData = async ()=>{
  // 问题校验
  let issueValidStr = ''
  try {
    await validList(pageContentRef.value.list)
  } catch (e) {
    e.forEach(item=>{
      let errMsg = item.errData.map(val=>val.msg).join(' ; ')
      issueValidStr += `<div>第${item.index+1}题错误，错误信息： <span style="color:red">${errMsg}</span> </div>`
    })
  }
  if(issueValidStr){
    issueValidStr = `题目校验失败：${issueValidStr} `
  }
  // 问卷校验
  let surveyValidStr = validSurvey(pageContentRef.value.surveyData);
  if(issueValidStr || surveyValidStr){
    await ElMessageBox.alert(`
    ${issueValidStr}
    ${surveyValidStr}
  `, '校验失败',{
      dangerouslyUseHTMLString: true,
    })
    return Promise.reject('校验失败')
  }else{
    return Promise.resolve()
  }
}

// 整理数据(部分字段需要处理)
const formatData = ()=>{
  return pageContentRef.value.list.map(item=>{
    if(item.type === 'multiple-check'){
      item.answer = item.answer.join(',')
    }
    return item
  })
}


const handlerPublish =async ()=>{
  await validateData();
  const data = formatData();
  await saveSurveyIssueApi({
    surId: +surId.value,
    data
  })
  await updateSurveyApi({
    ...pageContentRef.value.surveyData,
    state:'2'
  })
  proxy.$modal.msgSuccess("发布成功")
}

</script>

<template>
    <div class="w-full  flex flex-col design-box">
      <page-header v-model="activeIndex"  @onSave="handlerSave" @onPublish="handlerPublish" />
      <page-content :activeTab="activeIndex"  ref="pageContentRef" />
    </div>
</template>

<style scoped lang="scss">
.design-box{
  height:calc(100vh - 84px);
}
</style>
